package com.leoandroid.tool.toolsbox.new

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.room.Room
import com.leoandroid.tool.toolsbox.bean.NotesDbInfo
import com.leoandroid.tool.toolsbox.largeread.databinding.ActivityNoticesListBinding
import java.util.ArrayList

class NoticesListActivity : AppCompatActivity() {
    private var  dataBase: com.leoandroid.tool.toolsbox.bean.AppDataBase? = null
    private var databind: ActivityNoticesListBinding? = null
    private var notesInfo: ArrayList<NotesDbInfo>? = null
    private var adapter : com.leoandroid.tool.toolsbox.adapter.StarViewAdapter? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        databind = ActivityNoticesListBinding.inflate(layoutInflater)
        setContentView(databind?.root)
        initView()
    }

    override fun onRestart() {
        super.onRestart()
        initData()
    }

    private fun initView(){
        databind?.notesBack?.setOnClickListener {
            finish()
        }
        dataBase = Room.databaseBuilder(applicationContext, com.leoandroid.tool.toolsbox.bean.AppDataBase::class.java,"notes-location-db").build()
        initData()
        databind?.apply {
            addNotes.setOnClickListener {
                val intent = Intent(this@NoticesListActivity,AddNotesActivity::class.java)
                startActivity(intent)
            }
            notesBack.setOnClickListener { finish() }
            mTagCloudView.setOnTagClickListener { parent, view, position ->
                AddNotesActivity.startAddNotesActivity(
                    this@NoticesListActivity,
                    notesInfo!!.get(position).uid
                )
            }
        }
    }


    private fun initData(){
        Thread{
            run {
                notesInfo = dataBase?.notesInfo?.getAll() as ArrayList<NotesDbInfo>?
                this.runOnUiThread {
                    if(notesInfo!=null){
                        if (notesInfo!!.size>0){
                            adapter = com.leoandroid.tool.toolsbox.adapter.StarViewAdapter(
                                this@NoticesListActivity,
                                notesInfo
                            )
                            databind?.mTagCloudView?.setAdapter(adapter)
                            databind?.noteEmptyTv!!.visibility = View.GONE
                        }else{
                            databind?.noteEmptyTv!!.visibility = View.VISIBLE
                        }
                    }else{
                        databind?.noteEmptyTv!!.visibility = View.VISIBLE
                    }
                }
            }
        }.start()
    }
}